package com.videoweb.interfaces.web;

import com.videoweb.domain.agent.valueobject.ModelConfig;
import com.videoweb.infrastructure.ai.SiliconFlowApiClient;
import dev.langchain4j.model.openai.OpenAiChatModel;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 聊天控制器
 * 提供基础的AI聊天功能
 */
@Slf4j
@RestController
@RequestMapping("/api/chat")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class ChatController {
    
    private final SiliconFlowApiClient aiClient;


    /**
     * 简单聊天接口
     */
    @PostMapping("/simple")
    public ResponseEntity<Map<String, Object>> simpleChat(@RequestBody ChatRequest request) {
        try {


            log.info("收到简单聊天请求: {}", request.getMessage());
            
            // 使用默认配置
            ModelConfig config = ModelConfig.createDefault();
            String response = aiClient.chat(request.getMessage(), config);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("response", response);
            result.put("model", config.getModelName());
            result.put("tokenCount", aiClient.estimateTokenCount(response));
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("简单聊天请求失败", e);
            
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("error", e.getMessage());
            
            return ResponseEntity.status(500).body(error);
        }
    }
    
    /**
     * 带系统提示词的聊天
     */
    @PostMapping("/with-prompt")
    public ResponseEntity<Map<String, Object>> chatWithPrompt(@RequestBody ChatWithPromptRequest request) {
        try {
            log.info("收到带提示词的聊天请求");
            
            ModelConfig config = request.getConfig() != null ? request.getConfig() : ModelConfig.createDefault();
            String response = aiClient.chatWithSystemPrompt(
                request.getSystemPrompt(), 
                request.getMessage(), 
                config
            );
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("response", response);
            result.put("model", config.getModelName());
            result.put("systemPrompt", request.getSystemPrompt());
            result.put("tokenCount", aiClient.estimateTokenCount(response));
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("带提示词的聊天请求失败", e);
            
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("error", e.getMessage());
            
            return ResponseEntity.status(500).body(error);
        }
    }
    
    /**
     * 代码生成聊天
     */
    @PostMapping("/code")
    public ResponseEntity<Map<String, Object>> codeChat(@RequestBody CodeChatRequest request) {
        try {
            log.info("收到代码生成请求: {}", request.getLanguage());
            
            // 使用代码生成优化配置
            ModelConfig config = ModelConfig.createForCodeGeneration();
            
            // 构建代码生成的系统提示词
            String systemPrompt = buildCodeSystemPrompt(request.getLanguage(), request.getFramework());
            
            String response = aiClient.chatWithSystemPrompt(systemPrompt, request.getMessage(), config);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("response", response);
            result.put("model", config.getModelName());
            result.put("language", request.getLanguage());
            result.put("framework", request.getFramework());
            result.put("tokenCount", aiClient.estimateTokenCount(response));
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("代码生成请求失败", e);
            
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("error", e.getMessage());
            
            return ResponseEntity.status(500).body(error);
        }
    }
    
    /**
     * API健康检查
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> health() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            boolean isHealthy = aiClient.isHealthy();
            result.put("status", isHealthy ? "healthy" : "unhealthy");
            result.put("aiService", "siliconflow");
            result.put("timestamp", System.currentTimeMillis());
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("健康检查失败", e);
            result.put("status", "error");
            result.put("error", e.getMessage());
            
            return ResponseEntity.status(500).body(result);
        }
    }
    
    /**
     * 构建代码生成的系统提示词
     */
    private String buildCodeSystemPrompt(String language, String framework) {
        StringBuilder prompt = new StringBuilder();
        prompt.append("你是一个专业的").append(language != null ? language : "Java").append("开发助手。");
        
        if (framework != null) {
            prompt.append("特别擅长").append(framework).append("框架开发。");
        }
        
        prompt.append("请遵循以下规则：\n");
        prompt.append("1. 生成的代码要结构清晰，有适当的注释\n");
        prompt.append("2. 遵循最佳实践和编码规范\n");
        prompt.append("3. 包含必要的异常处理\n");
        prompt.append("4. 如果是Spring Boot项目，使用相应的注解和模式\n");
        prompt.append("5. 代码要可以直接运行，包含必要的导入语句\n");
        prompt.append("6. 为复杂逻辑提供简要说明");
        
        return prompt.toString();
    }
    
    // DTO类定义
    public static class ChatRequest {
        @NotBlank
        @Size(max = 5000)
        private String message;
        
        // getter和setter
        public String getMessage() { return message; }
        public void setMessage(String message) { this.message = message; }
    }
    
    public static class ChatWithPromptRequest {
        @NotBlank
        private String systemPrompt;
        @NotBlank
        @Size(max = 5000)
        private String message;
        private ModelConfig config;
        
        // getter和setter
        public String getSystemPrompt() { return systemPrompt; }
        public void setSystemPrompt(String systemPrompt) { this.systemPrompt = systemPrompt; }
        public String getMessage() { return message; }
        public void setMessage(String message) { this.message = message; }
        public ModelConfig getConfig() { return config; }
        public void setConfig(ModelConfig config) { this.config = config; }
    }
    
    public static class CodeChatRequest {
        @NotBlank
        @Size(max = 5000)
        private String message;
        private String language = "java";
        private String framework;
        
        // getter和setter
        public String getMessage() { return message; }
        public void setMessage(String message) { this.message = message; }
        public String getLanguage() { return language; }
        public void setLanguage(String language) { this.language = language; }
        public String getFramework() { return framework; }
        public void setFramework(String framework) { this.framework = framework; }
    }
}